package com.jingran.satokennetty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Getter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty启动和初始化
 */
@Component
public class SocketServer {
    @Resource
    private SocketInitializer socketInitializer;

    /**
     * 服务端启动配置类
     * 绑定端口
     */
    @Getter
    private ServerBootstrap serverBootstrap;

    /**
     * 启动netty服务器
     */
    public void start(){
        this.init();
        this.serverBootstrap.bind(8080);
    }

    /**
     * 初始化netty配置
     */
    private void init() {
        // 创建两个线程组，bossGroup为接收请求的线程组，一般1-2个就行
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 实际工作的线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(bossGroup, workerGroup)
                // 配置为nio类型
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                // 加入自己的初始化器
                .childHandler(this.socketInitializer);
    }
}
